package com.smsservice.servico;

import java.sql.ResultSet;
import java.sql.SQLException;

import android.app.Activity;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.IBinder;
import android.telephony.SmsManager;
import android.util.Log;
import android.widget.Toast;

import com.smsservice.banco.ConexaoBD;
import com.smsservice.bean.SmsBean;

/**
 * Classe que representa o servi��o que consulta e envia os SMS
 * @author Vitor
 *
 */
@SuppressWarnings("deprecation")
public class SendSmsService extends Service {

	// Constante com o nome das preferencias salvas
	public static final String PREFS_NAME = "ConfigServidorPref";

	String url;
	String dbName;
	String userName;
	String password;

	String enderecoIP;
	String porta;
	String nomeBaseDados;

	ResultSet rs = null;
	ConexaoBD conn = null;
	int limite;
	String sql;
	boolean continuar = true;
	

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void onStart(Intent intent, int startId) {
		// TODO Auto-generated method stub
		super.onStart(intent, startId);
		Toast.makeText(this, "Serviço iniciado com sucesso!", Toast.LENGTH_SHORT).show();

		Thread t = new Thread() {
			public void run() {
				getConfiguracoes();
				
				//conn = ConexaoBD.getDbCon(url, dbName, userName, password);

				try {

					limite = 5;

					while (continuar) {
						sql = "SELECT id, destino, mensagem, data, status from sms where status = '0' " + "limit " + String.valueOf(limite);
						Log.i("sms", "SQL> "+sql);
						rs = conn.query(sql);

						while (rs.next()) {
							SmsBean sms = new SmsBean();
							sms.setId(rs.getInt("id"));
							sms.setDestino(rs.getString("destino"));
							sms.setMensagem(rs.getString("mensagem"));
							sms.setData(rs.getDate("data"));
							sms.setStatus(rs.getString("status"));

							// envia sms
							sendSMS(sms.getDestino(), sms.getMensagem());

							// atualiza status da mensagem para enviada = 1
							atualizaStatusSMS(conn, sms.getId());
						}

						Thread.sleep(5000);
					}

				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		};
		t.start();
	}
	
	private void getConfiguracoes(){
		// Restaura as preferencias gravadas
		SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
		enderecoIP = settings.getString("EnderecoIP", "");
		porta = String.valueOf(settings.getString("Porta", ""));

		// Monta a URL do banco
		url = "jdbc:mysql://" + enderecoIP + ":" + porta + "/";

		dbName = settings.getString("NomeBaseDados", "");
		userName = settings.getString("nomeUsuario", "");
		password = settings.getString("Senha", "");
		
		Log.i("SMS", "Url conexao: " + url);
	}

	public void atualizaStatusSMS(ConexaoBD conn, long idSMS) {
		try {
			conn.insert("UPDATE sms SET status = '1' WHERE id = " + String.valueOf(idSMS));
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	// ---sends an SMS message to another device---
	private void sendSMS(String phoneNumber, String message) {
		String SENT = "SMS_SENT";
		String DELIVERED = "SMS_DELIVERED";

		PendingIntent sentPI = PendingIntent.getBroadcast(this, 0, new Intent(SENT), 0);

		PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0, new Intent(DELIVERED), 0);

		// ---when the SMS has been sent---
		registerReceiver(new BroadcastReceiver() {
			@Override
			public void onReceive(Context arg0, Intent arg1) {
				switch (getResultCode()) {
				case Activity.RESULT_OK:
					Toast.makeText(getBaseContext(), "SMS Enviada", Toast.LENGTH_SHORT).show();
					break;
				case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
					Toast.makeText(getBaseContext(), "Falha generica", Toast.LENGTH_SHORT).show();
					break;
				case SmsManager.RESULT_ERROR_NO_SERVICE:
					Toast.makeText(getBaseContext(), "Sem serviço", Toast.LENGTH_SHORT).show();
					break;
				case SmsManager.RESULT_ERROR_NULL_PDU:
					Toast.makeText(getBaseContext(), "Null PDU", Toast.LENGTH_SHORT).show();
					break;
				case SmsManager.RESULT_ERROR_RADIO_OFF:
					Toast.makeText(getBaseContext(), "Radio off", Toast.LENGTH_SHORT).show();
					break;
				}
			}
		}, new IntentFilter(SENT));

		// ---when the SMS has been delivered--- 
		registerReceiver(new BroadcastReceiver() {
			@Override
			public void onReceive(Context arg0, Intent arg1) {
				switch (getResultCode()) {
				case Activity.RESULT_OK:
					Toast.makeText(getBaseContext(), "SMS entregue", Toast.LENGTH_SHORT).show();
					break;
				case Activity.RESULT_CANCELED:
					Toast.makeText(getBaseContext(), "SMS não entregue", Toast.LENGTH_SHORT).show();
					break;
				}
			}
		}, new IntentFilter(DELIVERED));

		SmsManager sms = SmsManager.getDefault();
		sms.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI);
	}

	@Override
	public void onDestroy() {
		Log.i("sms", "Service finalizado");
		continuar = false;
		super.onDestroy();
		stopSelf();
	}

}
